package com.example.gm.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.gm.entity.ApiResult;
import com.example.gm.entity.LoginEntity;
import com.example.gm.entity.SecretEntity;
import com.example.gm.service.GmApiService;
import com.fasterxml.jackson.core.JsonProcessingException;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/pub/gm/*")
@CrossOrigin
public class GmPubController {
	@Autowired
	GmApiService gmApiService;
	
	private Object ping(HttpServletRequest request) {
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		LocalDateTime now = LocalDateTime.now();
		return ApiResult.ok(request.getRemoteAddr() 
				+ ", "+now.format(formatter));
	}
	@PostMapping(value = "ping", produces = "application/json; charset=UTF-8")
	public Object pingPost(HttpServletRequest request) {
		return ping(request);
	}
	@GetMapping(value = "ping", produces = "application/json; charset=UTF-8")
	public Object pingGet(HttpServletRequest request) {
		return ping(request);
	}
	
	// 登录
	@PostMapping(value = "login", produces = "application/json; charset=UTF-8")
	public ApiResult login(@RequestBody LoginEntity entity) throws JsonProcessingException {
		return this.gmApiService.login(entity);
	}

	// 下载sm2公钥
	@PostMapping(value = "publickey", produces = "application/json; charset=UTF-8")
	public Object publickey() {
		try {
			return this.gmApiService.publickey();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return ApiResult.error(e.getMessage());
		}
	}

	// 测试加密
	@PostMapping(value = "encrypt", produces = "application/json; charset=UTF-8")
	public Object encrypt(@RequestBody SecretEntity params) {
		try {
			return this.gmApiService.encrypt(params);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return ApiResult.error(e.getMessage());
		}
	}
	// 测试解密
	@PostMapping(value = "decrypt", produces = "application/json; charset=UTF-8")
	public Object decrypt(@RequestBody SecretEntity params) {
		try {
			return this.gmApiService.decrypt(params);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return ApiResult.error(e.getMessage());
		}
	}
	
}
